<template>
  <div class="message-item" :class="messageClasses" @contextmenu="handleRightClick">
    <!-- 消息头像 -->
    <div v-if="showAvatar" class="message-avatar">
      <div class="avatar" :class="avatarClass">
        <img v-if="avatarUrl" :src="avatarUrl" :alt="senderName" />
        <el-icon v-else>
          <component :is="avatarIcon" />
        </el-icon>
      </div>
    </div>
    
    <!-- 消息内容区域 -->
    <div class="message-content">
      <!-- 消息头部信息 -->
      <div v-if="showHeader" class="message-header">
        <span class="sender-name">{{ senderName }}</span>
        <span v-if="showTimestamp" class="message-time">
          {{ formatTime(message.timestamp) }}
        </span>
        <div class="message-meta">
          <!-- 消息类型标识 -->
          <el-tag v-if="showMessageType" :type="messageTypeColor" size="small" class="type-tag">
            {{ messageTypeText }}
          </el-tag>
          
          <!-- 流式状态指示器 -->
          <div v-if="isStreaming" class="streaming-indicator">
            <el-icon class="rotating"><Loading /></el-icon>
            <span>生成中...</span>
          </div>
        </div>
      </div>
      
      <!-- 消息主体 -->
      <div class="message-body">
        <!-- 文本消息 -->
        <div v-if="message.type === 'text'" class="text-content">
          <div v-if="isStreaming" class="streaming-text">
            <span class="streamed-content">{{ displayContent }}</span>
            <span v-if="showCursor" class="typing-cursor">|</span>
          </div>
          <div v-else class="static-text" v-html="formattedContent"></div>
        </div>
        
        <!-- 任务消息 -->
        <div v-else-if="message.type === 'task'" class="task-content">
          <div class="task-header">
            <el-icon class="task-icon"><List /></el-icon>
            <span class="task-title">任务分解完成</span>
          </div>
          <div class="task-description">
            {{ message.content }}
          </div>
          <div v-if="taskData" class="task-list">
            <TaskDisplay :tasks="taskData" />
          </div>
        </div>
        
        <!-- 系统消息 -->
        <div v-else-if="message.type === 'system'" class="system-content">
          <div class="system-header">
            <el-icon class="system-icon"><InfoFilled /></el-icon>
            <span class="system-title">系统消息</span>
          </div>
          <div class="system-text">{{ message.content }}</div>
          <div v-if="systemData" class="system-details">
            <pre>{{ JSON.stringify(systemData, null, 2) }}</pre>
          </div>
        </div>
        
        <!-- 错误消息 -->
        <div v-else-if="message.type === 'error'" class="error-content">
          <div class="error-header">
            <el-icon class="error-icon"><WarningFilled /></el-icon>
            <span class="error-title">错误信息</span>
          </div>
          <div class="error-text">{{ message.content }}</div>
          <div v-if="errorDetails" class="error-details">
            <el-collapse>
              <el-collapse-item title="详细信息" name="details">
                <pre>{{ errorDetails }}</pre>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
        
        <!-- 自定义内容 -->
        <div v-else class="custom-content">
          <slot name="custom-content" :message="message">
            <div class="fallback-content">
              <span>{{ message.content }}</span>
            </div>
          </slot>
        </div>
      </div>
      
      <!-- 消息操作按钮 -->
      <transition name="fade">
        <div v-if="showActions" class="message-actions" @click.stop>
          <el-tooltip content="复制内容">
            <el-button
              type="text"
              :icon="Copy"
              @click="handleCopy"
              class="action-button"
              size="small"
            />
          </el-tooltip>
          
          <el-tooltip v-if="canRetry" content="重新生成">
            <el-button
              type="text"
              :icon="RefreshRight"
              @click="handleRetry"
              class="action-button"
              size="small"
            />
          </el-tooltip>
          
          <el-tooltip v-if="canEdit" content="编辑消息">
            <el-button
              type="text"
              :icon="Edit"
              @click="handleEdit"
              class="action-button"
              size="small"
            />
          </el-tooltip>
          
          <el-tooltip v-if="canDelete" content="删除消息">
            <el-button
              type="text"
              :icon="Delete"
              @click="handleDelete"
              class="action-button delete-button"
              size="small"
            />
          </el-tooltip>
          
          <!-- 更多操作菜单 -->
          <el-dropdown @command="handleMenuAction" trigger="click">
            <el-button type="text" :icon="MoreFilled" class="action-button" size="small" />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="quote" :icon="ChatDotRound">
                  引用回复
                </el-dropdown-item>
                <el-dropdown-item command="share" :icon="Share">
                  分享消息
                </el-dropdown-item>
                <el-dropdown-item command="bookmark" :icon="Star">
                  收藏消息
                </el-dropdown-item>
                <el-dropdown-item command="report" :icon="Warning" divided>
                  举报消息
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </transition>
      
      <!-- 消息状态指示 -->
      <div v-if="showStatus" class="message-status">
        <div v-if="message.metadata?.confidence" class="confidence-score">
          <span class="confidence-label">置信度:</span>
          <el-progress
            :percentage="Math.round(message.metadata.confidence * 100)"
            :stroke-width="4"
            :show-text="false"
            class="confidence-bar"
          />
          <span class="confidence-value">{{ Math.round(message.metadata.confidence * 100) }}%</span>
        </div>
        
        <div v-if="wordCount > 0" class="word-count">
          {{ wordCount }} 字
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ChatMessage } from '@/types'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import TaskDisplay from '../task/TaskDisplay.vue'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'

// Props
interface Props {
  message: ChatMessage
  isStreaming?: boolean
  showAvatar?: boolean
  showTimestamp?: boolean
  showHeader?: boolean
  showActions?: boolean
  showStatus?: boolean
  showMessageType?: boolean
  autoScroll?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  isStreaming: false,
  showAvatar: true,
  showTimestamp: true,
  showHeader: true,
  showActions: true,
  showStatus: false,
  showMessageType: false,
  autoScroll: true
})

// Emits
interface Emits {
  action: [action: string, messageId: string]
  retry: [messageId: string]
  copy: [messageId: string]
  delete: [messageId: string]
  edit: [messageId: string]
}

const emit = defineEmits<Emits>()

// 状态
const displayContent = ref('')
const showCursor = ref(false)
const isHovered = ref(false)
const streamingTimer = ref<NodeJS.Timeout>()

// Markdown 解析器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: (str, lang) => {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value
      } catch {}
    }
    return ''
  }
})

// 计算属性
const messageClasses = computed(() => ({
  'message-item': true,
  [`message-item--${props.message.role}`]: true,
  [`message-item--${props.message.type}`]: true,
  'message-item--streaming': props.isStreaming,
  'message-item--hovered': isHovered.value
}))

const senderName = computed(() => {
  switch (props.message.role) {
    case 'user': return '您'
    case 'assistant': return 'AI助手'
    case 'system': return '系统'
    default: return props.message.role
  }
})

const avatarClass = computed(() => ({
  avatar: true,
  [`avatar--${props.message.role}`]: true
}))

const avatarIcon = computed(() => {
  switch (props.message.role) {
    case 'user': return 'User'
    case 'assistant': return 'Robot'
    case 'system': return 'Setting'
    default: return 'User'
  }
})

const avatarUrl = computed(() => {
  // 可以根据需要返回头像URL
  return props.message.metadata?.avatarUrl || null
})

const messageTypeText = computed(() => {
  switch (props.message.type) {
    case 'text': return '文本'
    case 'task': return '任务'
    case 'system': return '系统'
    case 'error': return '错误'
    default: return props.message.type
  }
})

const messageTypeColor = computed(() => {
  switch (props.message.type) {
    case 'text': return 'info'
    case 'task': return 'warning'
    case 'system': return 'info'
    case 'error': return 'danger'
    default: return 'info'
  }
})

const formattedContent = computed(() => {
  if (props.message.type === 'text') {
    return md.render(props.message.content)
  }
  return props.message.content
})

const taskData = computed(() => {
  return props.message.metadata?.tasks || null
})

const systemData = computed(() => {
  if (props.message.type === 'system' && props.message.metadata) {
    const { avatarUrl, ...data } = props.message.metadata
    return Object.keys(data).length > 0 ? data : null
  }
  return null
})

const errorDetails = computed(() => {
  return props.message.metadata?.error || props.message.metadata?.details || null
})

const wordCount = computed(() => {
  return props.message.content.length
})

const canRetry = computed(() => {
  return props.message.role === 'user' || 
         (props.message.role === 'assistant' && props.message.type === 'error')
})

const canEdit = computed(() => {
  return props.message.role === 'user'
})

const canDelete = computed(() => {
  return !props.isStreaming
})

// 方法
const formatTime = (date: Date) => {
  return formatDistanceToNow(date, { 
    addSuffix: true, 
    locale: zhCN 
  })
}

const startStreaming = (content: string) => {
  displayContent.value = ''
  showCursor.value = true
  
  let index = 0
  const chars = Array.from(content) // 支持 Unicode 字符
  
  const stream = () => {
    if (index < chars.length) {
      displayContent.value += chars[index]
      index++
      
      // 自动滚动
      if (props.autoScroll) {
        nextTick(() => {
          const element = document.querySelector('.message-list')
          if (element) {
            element.scrollTop = element.scrollHeight
          }
        })
      }
      
      streamingTimer.value = setTimeout(stream, 30) // 30ms 间隔
    } else {
      showCursor.value = false
    }
  }
  
  stream()
}

const stopStreaming = () => {
  if (streamingTimer.value) {
    clearTimeout(streamingTimer.value)
    streamingTimer.value = undefined
  }
  showCursor.value = false
}

const handleRightClick = (event: MouseEvent) => {
  event.preventDefault()
  // 可以在这里实现右键菜单
  console.log('Right click on message:', props.message.id)
}

const handleCopy = async () => {
  try {
    await navigator.clipboard.writeText(props.message.content)
    ElMessage.success('内容已复制到剪贴板')
    emit('copy', props.message.id)
  } catch (error) {
    console.error('Failed to copy:', error)
    ElMessage.error('复制失败')
  }
}

const handleRetry = () => {
  emit('retry', props.message.id)
}

const handleEdit = () => {
  emit('edit', props.message.id)
}

const handleDelete = () => {
  ElMessageBox.confirm(
    '确定要删除这条消息吗？',
    '确认删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    emit('delete', props.message.id)
  }).catch(() => {
    // 用户取消
  })
}

const handleMenuAction = (command: string) => {
  switch (command) {
    case 'quote':
      handleQuote()
      break
    case 'share':
      handleShare()
      break
    case 'bookmark':
      handleBookmark()
      break
    case 'report':
      handleReport()
      break
  }
}

const handleQuote = () => {
  // 实现引用回复功能
  emit('action', 'quote', props.message.id)
}

const handleShare = () => {
  // 实现分享功能
  emit('action', 'share', props.message.id)
}

const handleBookmark = () => {
  // 实现收藏功能
  emit('action', 'bookmark', props.message.id)
}

const handleReport = () => {
  // 实现举报功能
  emit('action', 'report', props.message.id)
}

// 监听流式状态变化
watch(() => props.isStreaming, (streaming) => {
  if (streaming) {
    startStreaming(props.message.content)
  } else {
    stopStreaming()
    displayContent.value = props.message.content
  }
})

// 监听消息内容变化（流式更新）
watch(() => props.message.content, (newContent) => {
  if (props.isStreaming) {
    // 在流式模式下更新显示内容
    displayContent.value = newContent
  }
})

// 生命周期
onMounted(() => {
  if (props.isStreaming) {
    startStreaming(props.message.content)
  } else {
    displayContent.value = props.message.content
  }
})

onUnmounted(() => {
  stopStreaming()
})
</script>

<style lang="scss" scoped>
.message-item {
  @include flex-start;
  gap: var(--spacing-sm);
  padding: var(--spacing-md) 0;
  position: relative;
  
  &:hover {
    .message-actions {
      opacity: 1;
      visibility: visible;
    }
  }
  
  // 用户消息样式
  &.message-item--user {
    flex-direction: row-reverse;
    
    .message-content {
      background: var(--chat-user-bg);
      border-radius: var(--border-radius-large) var(--border-radius-base) 
                     var(--border-radius-base) var(--border-radius-large);
    }
    
    .message-header {
      text-align: right;
    }
  }
  
  // AI助手消息样式
  &.message-item--assistant {
    .message-content {
      background: var(--chat-assistant-bg);
      border-radius: var(--border-radius-base) var(--border-radius-large)
                     var(--border-radius-large) var(--border-radius-base);
    }
  }
  
  // 系统消息样式
  &.message-item--system {
    justify-content: center;
    
    .message-content {
      background: var(--chat-system-bg);
      border-radius: var(--border-radius-base);
      text-align: center;
      max-width: 80%;
    }
    
    .message-avatar {
      display: none;
    }
  }
  
  // 错误消息样式
  &.message-item--error {
    .message-content {
      background: var(--chat-error-bg);
      border: 1px solid var(--danger-color);
      border-radius: var(--border-radius-base);
    }
  }
  
  // 流式状态
  &.message-item--streaming {
    .message-content {
      position: relative;
      
      &::after {
        content: '';
        position: absolute;
        bottom: var(--spacing-sm);
        right: var(--spacing-sm);
        width: 8px;
        height: 8px;
        background: var(--primary-color);
        border-radius: 50%;
        @include pulse-animation;
      }
    }
  }
}

// 消息头像
.message-avatar {
  flex-shrink: 0;
}

.avatar {
  @include avatar(40px);
  @include flex-center;
  
  &.avatar--user {
    background: var(--primary-color-lighter);
    color: var(--primary-color);
  }
  
  &.avatar--assistant {
    background: var(--success-color-lighter);
    color: var(--success-color);
  }
  
  &.avatar--system {
    background: var(--info-color-lighter);
    color: var(--info-color);
  }
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

// 消息内容
.message-content {
  flex: 1;
  min-width: 0;
  padding: var(--spacing-md);
  position: relative;
  max-width: 75%;
  
  @include respond-to(md) {
    max-width: 90%;
  }
}

// 消息头部
.message-header {
  @include flex-between;
  margin-bottom: var(--spacing-sm);
  align-items: flex-start;
}

.sender-name {
  font-weight: 600;
  color: var(--text-color-primary);
  font-size: var(--font-size-small);
}

.message-time {
  font-size: var(--font-size-extra-small);
  color: var(--text-color-secondary);
  white-space: nowrap;
}

.message-meta {
  @include flex-center;
  gap: var(--spacing-xs);
}

.type-tag {
  font-size: var(--font-size-extra-small);
}

.streaming-indicator {
  @include flex-center;
  gap: var(--spacing-xs);
  font-size: var(--font-size-extra-small);
  color: var(--primary-color);
  
  .rotating {
    @include loading-animation;
  }
}

// 消息主体
.message-body {
  line-height: 1.6;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

// 文本内容
.text-content {
  .streaming-text {
    position: relative;
    
    .typing-cursor {
      display: inline-block;
      width: 1px;
      margin-left: 2px;
      background: var(--primary-color);
      animation: blink 1s infinite;
    }
  }
  
  .static-text {
    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      margin: var(--spacing-md) 0 var(--spacing-sm) 0;
      color: var(--text-color-primary);
    }
    
    :deep(p) {
      margin: var(--spacing-sm) 0;
    }
    
    :deep(code) {
      background: var(--bg-color-light);
      padding: 2px 4px;
      border-radius: var(--border-radius-small);
      font-size: 0.9em;
    }
    
    :deep(pre) {
      background: var(--bg-color-light);
      padding: var(--spacing-md);
      border-radius: var(--border-radius-base);
      overflow-x: auto;
      margin: var(--spacing-md) 0;
      
      code {
        background: none;
        padding: 0;
      }
    }
    
    :deep(blockquote) {
      border-left: 4px solid var(--primary-color);
      padding-left: var(--spacing-md);
      margin: var(--spacing-md) 0;
      color: var(--text-color-secondary);
    }
    
    :deep(ul), :deep(ol) {
      padding-left: var(--spacing-lg);
      margin: var(--spacing-sm) 0;
    }
    
    :deep(table) {
      width: 100%;
      border-collapse: collapse;
      margin: var(--spacing-md) 0;
      
      th, td {
        border: 1px solid var(--border-color);
        padding: var(--spacing-sm);
        text-align: left;
      }
      
      th {
        background: var(--bg-color-light);
        font-weight: 600;
      }
    }
  }
}

// 任务内容
.task-content {
  .task-header {
    @include flex-start;
    gap: var(--spacing-sm);
    margin-bottom: var(--spacing-sm);
    
    .task-icon {
      color: var(--warning-color);
    }
    
    .task-title {
      font-weight: 600;
      color: var(--text-color-primary);
    }
  }
  
  .task-description {
    color: var(--text-color-secondary);
    margin-bottom: var(--spacing-md);
  }
  
  .task-list {
    border-top: 1px solid var(--border-color);
    padding-top: var(--spacing-md);
  }
}

// 系统内容
.system-content {
  .system-header {
    @include flex-start;
    gap: var(--spacing-sm);
    margin-bottom: var(--spacing-sm);
    
    .system-icon {
      color: var(--info-color);
    }
    
    .system-title {
      font-weight: 600;
      color: var(--text-color-primary);
    }
  }
  
  .system-text {
    color: var(--text-color-secondary);
  }
  
  .system-details {
    margin-top: var(--spacing-md);
    
    pre {
      background: var(--bg-color-dark);
      padding: var(--spacing-sm);
      border-radius: var(--border-radius-base);
      font-size: var(--font-size-small);
      overflow-x: auto;
    }
  }
}

// 错误内容
.error-content {
  .error-header {
    @include flex-start;
    gap: var(--spacing-sm);
    margin-bottom: var(--spacing-sm);
    
    .error-icon {
      color: var(--danger-color);
    }
    
    .error-title {
      font-weight: 600;
      color: var(--danger-color);
    }
  }
  
  .error-text {
    color: var(--text-color-secondary);
  }
  
  .error-details {
    margin-top: var(--spacing-md);
    
    pre {
      background: var(--bg-color-dark);
      padding: var(--spacing-sm);
      border-radius: var(--border-radius-base);
      font-size: var(--font-size-small);
      overflow-x: auto;
      color: var(--danger-color);
    }
  }
}

// 自定义内容
.custom-content {
  .fallback-content {
    color: var(--text-color-secondary);
    font-style: italic;
  }
}

// 消息操作
.message-actions {
  position: absolute;
  top: var(--spacing-sm);
  right: var(--spacing-sm);
  @include flex-center;
  gap: var(--spacing-xs);
  opacity: 0;
  visibility: hidden;
  transition: var(--transition-base);
  background: rgba(255, 255, 255, 0.9);
  border-radius: var(--border-radius-base);
  padding: var(--spacing-xs);
  box-shadow: var(--box-shadow-light);
  backdrop-filter: blur(4px);
  
  .action-button {
    width: 24px;
    height: 24px;
    
    &.delete-button {
      &:hover {
        color: var(--danger-color);
      }
    }
    
    &:hover {
      background: var(--bg-color-light);
    }
  }
}

// 消息状态
.message-status {
  @include flex-between;
  margin-top: var(--spacing-sm);
  padding-top: var(--spacing-sm);
  border-top: 1px solid var(--border-color-light);
  font-size: var(--font-size-extra-small);
  color: var(--text-color-secondary);
}

.confidence-score {
  @include flex-center;
  gap: var(--spacing-xs);
  
  .confidence-bar {
    width: 60px;
  }
}

.word-count {
  color: var(--text-color-placeholder);
}

// 动画
@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 暗色主题适配
@include dark-theme {
  .message-actions {
    background: rgba(0, 0, 0, 0.8);
  }
}
</style>